package org.hhf.ai.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChatQueues<E> {
    private static Map<Long,FixedSizeQueue> queueMap = new ConcurrentHashMap<>();
    private static ChatQueues instance = new ChatQueues();
    private static final int maxSize = 10;

    public static synchronized ChatQueues getInstance(){
        if (instance == null) {
            return new ChatQueues();
        }
        return instance;
    }

    /**
     * 清除queueMap缓存中的队列
     * @param conversationId
     */
    public void clearQueue(Long conversationId) {
        queueMap.remove(conversationId);
    }

    /**
     * 消息入队
     * @param msg
     * @return
     */
    public boolean offer(Long conversationId, String msg) {
        FixedSizeQueue queue = getQueue(conversationId);
        return queue.offer(msg);
    }

    /**
     * 消息出队
     * @return
     */
    public E poll(Long conversationId) {
        FixedSizeQueue<E> queue = getQueue(conversationId);
        return queue.poll();
    }

    public FixedSizeQueue<E> getQueue(Long conversationId) {
        FixedSizeQueue<E> queue = queueMap.get(conversationId);
        if (queue == null) {
            // 如果阻塞队列不存在则创建
            queue = new FixedSizeQueue(maxSize);
            queueMap.put(conversationId, queue);
        }
        return queue;
    }
}
